//
//  BedViewController.m
//  Nurse
//
//  Created by Sunny on 13-12-13.
//  Copyright (c) 2013年 RainSets. All rights reserved.
//

#import "BedViewController.h"
#import "BedCell.h"
#import "PatientInfoViewController.h"
#import "TestViewController.h"
#import "AppDelegate.h"

#import "BedScreeningView.h"

#import "PatientService.h"
#import "OperatorService.h"
#import "BedSmallCell.h"
#import "ScanService.h"
#import "MBProgressHUD.h"
#import "EGORefreshTableHeaderView.h"  //下来刷新


@interface BedViewController ()

@property(nonatomic,weak)IBOutlet UITableView *table;
@property(nonatomic,strong) AVAudioPlayer *player;  
//@property (nonatomic,strong) NSArray* patientDicts;
-(void)pushPatientView:(NSDictionary*) record;
-(void)onReceiveScanData:(NSNotification*)notification;

@end

@implementation BedViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
        [nc addObserver:self selector:@selector(onReceiveScanData:) name:@"bed" object:nil];
        
    }
    return self;
}


- (void)reloadTableViewDataSource{
    _reloading = YES;
    //开始刷新后执行后台线程，在此之前可以开启HUD或其他对UI进行阻塞
    //[NSThread detachNewThreadSelector:@selector(doInBackground) toTarget:self withObject:nil];
    //[self setupData];
    
}

//下拉松开刷新
- (void)doneLoadingTableViewData{
    NSLog(@"===加载完数据");
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.table];
    [self setupData];
}
#pragma mark –
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
} - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}
#pragma mark –
#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    [self reloadTableViewDataSource];
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    return _reloading;
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    return [NSDate date];
}

-(void)setupDataWithWardCode:(NSString*)wardCode{
    __weak BedViewController* this = self;
    [[OperatorService sharedInstance]setCurrentOperatorWardCode:wardCode];
    [self updateTitleWithWardCode:wardCode];
    [[PatientService sharedInstance]queryPatientsForWardCode:wardCode withSuccessHandler:^(id result) {
        if ([result isKindOfClass:[NSArray class]]) {
            [PatientService sharedInstance].patientDicts = result;
            [this.table reloadData];
        }
    } andFailHandler:^(NSError *error, NSString *title) {
        [[DataEngine sharedInstance]showMessage:[error description] withTitle:@"访问病区病人数据错误"];
    }];
}

-(void)setupData{
    NSString* wardCode = [[OperatorService sharedInstance]currentOperatorWardCode];
    if (wardCode != nil) {
        //NSString* wardCode = [wardCodes objectAtIndex:0];
        NSLog(@"wardCode:%@",wardCode);
        [self setupDataWithWardCode:wardCode];
    }else{
        [[DataEngine sharedInstance]showMessage:@"没有可用的病区" withTitle:@"数据错误"];
    }
}

-(void)updateTitleWithWardCode:(NSString*)wardCode{
    NSDictionary* ward = nil;
    for (NSDictionary* w in [[OperatorService sharedInstance]currentOperatorWards]) {
        if ([[w valueForKey:@"科室代码"]isEqualToString:wardCode]) {
            ward = w;
            break;
        }
    }
    if (ward != nil) {
        self.title = [ward valueForKey:@"科室名称"];
        
        AppDelegate  *appDelegate = App;
        //appDelegate.currentwardCode=[ward valueForKey:@"科室代码"];
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title  = @"南八楼";
//    [self setleftBarButtonItem:@"screening_leftBar.png" Event:@selector(leftBar_clicked:)];
     [self setleftBarButtonItem:@""orImaged:@"head-icon_01.png" Event:@selector(leftBar_clicked:)];
    [self setupData];
   // [self setrightBarButtonItem:@""orImaged:@"head-icon_02.png" Event:@selector(rightBar_clicked:)];
//    [[Captuvo sharedCaptuvoDeviceDebug] addCaptuvoDelegate:self];
//    [[Captuvo sharedCaptuvoDevice] startDecoderHardware] ;
//    [[Captuvo sharedCaptuvoDevice]enableCaptuvoDebug:NO];
   
    // bedNav.navigationBar.tintColor = NavigationBarColor;
    
   
    if (_refreshHeaderView == nil) {
        EGORefreshTableHeaderView *view1 = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0-self.table.bounds.size.height, self.view.frame.size.width, self.table.bounds.size.height)];
        view1.delegate = self;
        [self.table addSubview:view1];
        _refreshHeaderView = view1;
        // [view1 release];
    }
    [_refreshHeaderView refreshLastUpdatedDate];
    
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [App showTabbar];
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([PatientService sharedInstance].patientDicts) {
        NSLog(@"self.patientDicts is not nil .................");
        NSInteger count = [[PatientService sharedInstance].patientDicts count];
        
        NSLog(@"self.patientDicts count:%d .................",count);
        return (count+3)/3;
    }else{
        return 0;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 106.f;
}





-(void)onReceiveScanData:(NSNotification*)notification{
//-(void)decoderDataReceived:(NSString *)smdata{
  
    if ([self.navigationController topViewController] == self) {
        
        NSDictionary* userinfo = [notification userInfo];
        NSString* data = [userinfo valueForKey:@"data"];
        
        NSArray* datearray = [data componentsSeparatedByString:@"|"];
        NSString* datebz = [datearray objectAtIndex:0];
        
        if (![datebz isEqualToString:@"BR"] && ![datebz isEqualToString:@"SY"])
        {
         [[DataEngine sharedInstance]showMessage:@"错误的条码格式" withTitle:@"扫描错误"];
        }
        

        //[[DataEngine sharedInstance]showMessage:data withTitle:@"扫描器输入"];
        
        //NSString *topViewController = NSStringFromClass([self.navigationController.topViewController class]);
        
        //[[DataEngine sharedInstance]showMessage:topViewController withTitle:visibleViewController];

    if ([datebz isEqualToString:@"BR"]) {
            // [[DataEngine sharedInstance]showMessage:@"没有找到此条码对应的病人" withTitle:@"扫描错误1"];
            NSArray* brarray = [data componentsSeparatedByString:@"|"];
            if ([brarray count] ==2) {
                 //[[DataEngine sharedInstance]showMessage:@"没有找到此条码对应的病人" withTitle:@"扫描错误2"];
                NSString* zyh = [brarray objectAtIndex:1];
                bool is_found_zyh = NO;
                for (NSDictionary* record in [PatientService sharedInstance].patientDicts) {
                    NSString* dzyh = [record valueForKey:@"住院号"];
                    if ([dzyh isEqualToString:zyh]) {
                        is_found_zyh = YES;
                        
                        [self pushPatientView:record];
                        break;
                    }
                }
                if (is_found_zyh == NO) {
                    [[DataEngine sharedInstance]showMessage:@"没有找到此条码对应的病人" withTitle:@"扫描错误"];
                }
            }
            else{
                [[DataEngine sharedInstance]showMessage:@"错误的病人条码格式" withTitle:@"扫描错误"];
            }
            
            
        }
       if ([datebz isEqualToString:@"SY"])  //扫描各类条码自动切换至任务
        {
           
        [App setSelected:1];  //导航条切换
                
        [App tabbarSelect:1];  //导航按钮标志选中
         
        AppDelegate  *appDelegate = App;
        appDelegate.isScan=YES;  //传入变量isScan 触发在任务中的对应消息动作

            
        }


    
    }
        
        
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *identify = @"BedCell";
    
    BedCell *cell = (BedCell *)[tableView  dequeueReusableCellWithIdentifier:identify];
    if (!cell ) {
        cell = [[BedCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.indexPath = indexPath;
    
    NSInteger row = [indexPath row];
    
    for (int i=0; i<3; i++) {
        [cell setEnableColum:i];
        BedSmallCell* smallCell = nil;
        if (i==0) {
            smallCell = cell.btn1;
        }else if (i==1){
            smallCell = cell.btn2;
        }else if (i==2){
            smallCell = cell.btn3;
        }
        smallCell.hidden = NO;
        NSInteger index = row*3+i;
        if (index<[[PatientService sharedInstance].patientDicts count]) {
            NSDictionary* record = [[PatientService sharedInstance].patientDicts objectAtIndex:index];
                       if (smallCell != nil) {
               
               
                smallCell.lblPatientName.text = [record valueForKey:@"姓名"];
                smallCell.lblBedNumber.text = [record valueForKey:@"床位号"];
                smallCell.lblBedNoWithoutPatient.text = [record valueForKey:@"床位号"];
                smallCell.lblPatientID.text = [record valueForKey:@"住院号"];
                smallCell.imgimport.hidden=YES;
                smallCell.lblimport.hidden=YES;
                           
                           
                NSString* hldj=[record valueForKey:@"护理等级"];
               if([hldj isEqualToString:@"特级护理"])
               {
                   smallCell.imgimport.image=[UIImage imageNamed:@"bed-important_1.png"];
                   smallCell.imgimport.hidden=NO;
                   smallCell.lblimport.text=@"特";
                   smallCell.lblimport.hidden=NO;
                   
               }
                if([hldj isEqualToString:@"一级护理"])
                           {
                               smallCell.imgimport.image=[UIImage imageNamed:@"bed-important_2.png"];
                               smallCell.imgimport.hidden=NO;
                               smallCell.lblimport.text=@"I";
                                smallCell.lblimport.hidden=NO;
                               
                           }
                           if([hldj isEqualToString:@"二级护理"])
                           {
                               smallCell.imgimport.image=[UIImage imageNamed:@"bed-important_3.png"];
                               smallCell.imgimport.hidden=NO;
                               smallCell.lblimport.text=@"Ⅱ";
                               smallCell.lblimport.hidden=NO;
                               
                           }
                
                NSString* zyh = [record valueForKey:@"住院号"];
                if (zyh == nil) {
                    [cell setDisableColum:i];
                }
            }
                
        }else{
            [cell setDisableColum:i];
            smallCell.hidden = YES;
        }
    }
    
    
    //[cell setDisableColum:2];
    
    
    __weak typeof(self) weakSelf = self;
    //cell 选择的内容
   
    [cell setBedSeleted:^(NSIndexPath *indexPath,int column){
        DLog(@"indexPath.row=%d,colum=%d",indexPath.row,column);
        //TestViewController *vc =[[TestViewController alloc] initWithNibName:@"TestViewController" bundle:nil];
        NSInteger row = [indexPath row];
        NSInteger index = row*3+column;
        NSDictionary* record = [[PatientService sharedInstance].patientDicts objectAtIndex:index];
        [weakSelf pushPatientView:record];
    }];
    
    return  cell;
}


-(void)pushPatientView:(NSDictionary*) record{
    [[PatientService sharedInstance]setCurrentPatient:record];
    PatientInfoViewController *vc = [[PatientInfoViewController alloc] initWithNibName:@"PatientInfoViewController" bundle:nil];
    self.navigationController.hidesBottomBarWhenPushed = YES;
    vc.hidesBottomBarWhenPushed = YES;
    [App hideTabbar];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)popPatientView{
    [self.navigationController popViewControllerAnimated:YES];
}






-(void)leftBar_clicked:(id)sender
{
    

    
   NSString *soundFilePath = [[NSBundle mainBundle]pathForResource:@"sound"
                            ofType:	 @"wav"];
    
    NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

   
   
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL: newURL error: nil];
//    
//    newPlayer.delegate=self;
//    
   [self.player prepareToPlay];
//    
  [self.player play];
     BedScreeningView *screeningView = [[[NSBundle mainBundle] loadNibNamed:@"BedScreeningView" owner:self options:nil] firstObject];
     screeningView.parent = self;
     screeningView.frame=CGRectMake(-screeningView.table_View.frame.size.width, 0, screeningView.frame.size.width, screeningView.frame.size.height);
     [self.view.window addSubview:screeningView];
     //self.view.modalPresentationStyle=UIModalPresentationPageSheet;
     [UIView animateWithDuration:.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
     screeningView.frame=CGRectMake(0, 0, 320, screeningView.frame.size.height);
     } completion:^(BOOL finished) {
     
     }];
     
    
}



-(void)rightBar_clicked:(id)sender{
    
}



@end
